﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DeviceController.NetCoreServer.Services;
using DeviceController.Wpf.Common;
using System;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace DeviceController.Wpf.ViewModels
{
    public class TestWindowViewModel : ObservableObject, IViewAware
    {
        private readonly DeviceControllerClient _client;

        private readonly ViewContext _context;

        public TestWindowViewModel(ViewContext viewContext)
        {
            _context = viewContext;
            SendDataCommand = new RelayCommand(OnSendData);
            viewContext.TryGetValue("TcpClient", out DeviceControllerClient client);
            viewContext.Add("IsShowTestWindow",true);
            _client = client;
            _client.Received -= OnTcpClientReceived;
            _client.Received += OnTcpClientReceived;
            ViewContext = viewContext;
        }

        private void OnTcpClientReceived(object? sender, ReceivedEventArgs e)
        {
            var stringValue = Encoding.UTF8.GetString(e.ReceivedData);

            if (IsNeedUpdate)
            {
                ReceiveData = stringValue;
            }
        }

        public bool IsNeedUpdate { get; set; }

        private string? _receiveData;

        public string? ReceiveData
        {
            get { return _receiveData; }
            set { SetProperty(ref _receiveData, value); }
        }

        public string? SendData { get; set; }

        public ICommand SendDataCommand { get; set; }

        public ViewContext ViewContext { get; }

        private void OnSendData()
        {
            if (string.IsNullOrEmpty(SendData))
            {
                MessageBox.Show("请输入要发送的报文！");
                return;
            }

            try
            {
                var sendValue = Encoding.UTF8.GetBytes(SendData);
                _client.Send(sendValue);
            }
            catch (Exception)
            {
                MessageBox.Show("发送数据失败！");
            }
        }

        public bool CanClose()
        {
            return true;
        }

        public void OnClosed()
        {
            _client.Received -= OnTcpClientReceived;
            _context.Add("IsShowTestWindow", false);
        }
    }
}
